﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Teigha.Runtime;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using System.Text.RegularExpressions;
using System.IO;

namespace replaceName
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = @"                                  cccc      cc           cc        cccc     cc       cc
                                cc          cc cc     cc cc      cc         cc       cc
                              cc            cc   cc cc   cc     cc          cc       cc
                              cc            cc     cc    cc     cc          cc       cc
                                cc          cc           cc      cc          cc     cc
                                  cccc      cc           cc        cccc       cclcbcc";
            Console.WriteLine("\n\n\n");
            Console.WriteLine(str);
            Console.WriteLine("本操作不可逆，切记做好备份！！！");
            Console.WriteLine("本操作不可逆，切记做好备份！！！");
            Console.WriteLine("本操作不可逆，切记做好备份！！！");

            string helpPaper = "    原理是根据外部dwg文档名称中的图号修改dwg内的图号，约定文档的图号与图名之间以空格分隔，如：DL-00 目录.dwg，可以通过批量修改文件名的程序先把图纸文档名称修改了\n" +
                "    使用说明：\n" +
                "        1、输入需要修改的图纸所在文件夹完整路径，如：C:\\Users\\admin\\Desktop\\道路工程（强烈建议备份原图纸，修改操作不可逆）\n" +
                "        2、根据提示输入关键字以匹配dwg图纸中的图号，如：图纸中的图号为DL-00，那么关键字即为DL-或者DL\n" +
                "        3、本程序已自动忽略目录页和dxt.dwg、tk.dwg、tq.dwg文件，目录页请手动修改\n" +
                "        Enjoy it!";
            Console.WriteLine(helpPaper);

            List<string>pathname = Getpath();

            Console.WriteLine("请输入搜索的关键字,按回车键结束：");
            string selectKey = Console.ReadLine();

            for (int i = 0; i < pathname.Count; i++)
            {
                string[] arr = pathname[i].Split('\\');
                string[] picNums = arr[arr.Length - 1].Split(' ');
                string picNum = picNums[0];

                if (Regex.IsMatch(picNum, @"00|dxt|DXT|TQ|tq|TK|tk"))
                    continue;
                EditName(pathname[i], selectKey,picNum);
            }
            Console.WriteLine("修改完成，按任意键退出。");
            Console.ReadKey();
        }
        /// <summary>
        /// 通过读取用户输入的文件夹地址，搜索文件夹中所有的dwg文件
        /// </summary>
        /// <returns>返回所有文件的地址列表</returns>
        static List<string> Getpath()
        {
            var pathName = new List<string> { };
            // 根据文件夹依次打开文件
            Console.WriteLine("请输入文件夹地址,按回车键结束：");
            string dirPath = Console.ReadLine();
            if (Directory.Exists(dirPath))
            {
                DirectoryInfo root = new DirectoryInfo(dirPath);
                FileInfo[] files = root.GetFiles();
                int fileNum = files.Length;
                Console.WriteLine("文件夹中共" + fileNum + "个文件\n点击确定进入下一步");
                Console.WriteLine("文件为：");

                // 遍历整个文件夹内文件
                foreach (var item in files)
                {
                    // 打开cad文件
                    if (Regex.IsMatch(item.FullName, @".dwg"))
                    {
                        pathName.Add(item.FullName);
                        Console.WriteLine(item.FullName);
                    }
                }
            }
            return pathName;
        }
        
        /// <summary>
        /// 修改图号的核心代码
        /// </summary>
        /// <param name="pathname"></param>
        /// <param name="keyword"></param>
        /// <param name="replaceName"></param>
        static void EditName(string pathname,string keyword,string replaceName)
        {
            //string pathname = @"C:\Users\BOBO\Desktop\DL-00 目录+图框.dwg";
            
            using (Services svc = new Services())
            {
                Database acCurDb = new Database(false, false);

                //string strSplit = "\\";
                //string[] arr = Regex.Split(pathname[i], strSplit, RegexOptions.IgnoreCase);
                //string fileName = arr[arr.Length];
                //string[] picNums = Regex.Split(fileName, " ", RegexOptions.IgnoreCase);
                //string picNum = picNums[picNums.Length];


                acCurDb.ReadDwgFile(pathname, FileShare.Read, false, null);
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    // 以读模式打开 Block 表
                    BlockTable acBlkTbl;
                    acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable;
                    //建议可以用linq去进行图元筛选获取到自己想要的图元
                    BlockTableRecord btrec = (BlockTableRecord)acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);  //获取块表
                    foreach (ObjectId objid in btrec)
                    {
                        Entity ent = acTrans.GetObject(objid, OpenMode.ForWrite) as Entity;
                        if (ent.GetType().Name == "DBText")
                        {
                            DBText txt = (DBText)ent;
                            //string oldTxt = txt.TextString;
                            if (Regex.IsMatch(txt.TextString, keyword))
                                txt.TextString = replaceName;
                            //Console.WriteLine(txt.TextString);
                        }
                    }

                    BlockTableRecord btrec1 = (BlockTableRecord)acTrans.GetObject(acBlkTbl[BlockTableRecord.PaperSpace], OpenMode.ForWrite);  //获取块表
                    foreach (ObjectId objid in btrec1)
                    {
                        Entity ent = acTrans.GetObject(objid, OpenMode.ForWrite) as Entity;
                        if (ent.GetType().Name == "DBText")
                        {
                            DBText txt = (DBText)ent;
                            //string oldTxt = txt.TextString;
                            if (Regex.IsMatch(txt.TextString, keyword))
                                txt.TextString = replaceName;
                            //Console.WriteLine(txt.TextString);
                        }
                    }
                    acTrans.Commit();
                    acCurDb.Save();
                    acCurDb.Dispose();
                }
                Console.WriteLine($"{pathname}，修改成功！");
            }
        }
    }
}
